package com.leyou.user.service;

import com.leyou.user.mapper.ImageMapper;
import com.leyou.user.mapper.InfoMapper;
import com.leyou.user.pojo.Image;
import com.leyou.user.pojo.Info;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class InfoService {

    @Autowired
    private InfoMapper infoMapper;

    @Autowired
    private ImageMapper imageMapper;

    @Transactional
    public void addInfo(Info info) {
        Info info2 = new Info();
        info2.setUserId(info.getUserId());
        Info info1 = this.infoMapper.selectOne(info2);
        if(info1==null){
            this.infoMapper.insertSelective(info);
        }else {
            this.infoMapper.updateByPrimaryKeySelective(info);
        }
        List<String> imgs = new ArrayList<>();
        if(!info.getImages().isEmpty()){
            imgs = info.getImages().stream().map(image -> image.getImage()).collect(Collectors.toList());
        }
        if(info.getImages().isEmpty() || !imgs.contains(info.getImage())){
            Image image = new Image();
            image.setImage(info.getImage());
            image.setInfoId(info.getId());
            this.imageMapper.insertSelective(image);
        }
    }

    public Info findInfo(Long uid) {
        Info info = new Info();
        info.setUserId(uid);
        Info info1 = this.infoMapper.selectOne(info);
        Image image = new Image();
        image.setInfoId(info1.getId());
        List<Image> images = this.imageMapper.select(image);
        info1.setImages(images);
        return info1;
    }

    @Transactional
    public void addImage(Info info) {
        Info info1 = new Info();
        info1.setId(info.getId());
        info1.setImage(info.getImage());
        Info info2 = this.infoMapper.selectByPrimaryKey(info.getId());
        this.infoMapper.updateByPrimaryKeySelective(info1);
    }

    public void deleteImage(Image image) {
        this.imageMapper.delete(image);
    }
}